package com.feihua.starter.web.modules.hdb.mvc;


import com.feihua.framework.rest.ResponseJsonRender;
import com.feihua.framework.rest.interceptor.RepeatFormValidator;
import com.feihua.framework.rest.modules.common.mvc.BaseController;
import com.feihua.starter.comm.Constants;
import com.feihua.starter.service.api.ApiHdbActivityPoService;
import com.feihua.starter.service.api.ApiHdbImagePoService;
import com.feihua.starter.service.api.ApiHdbScenicSpotPoService;
import com.feihua.starter.service.api.ApiHdbUserExtendPoService;
import com.feihua.starter.service.modules.hdb.dto.HdbActivityDto;
import com.feihua.starter.service.modules.hdb.dto.HdbReviewDto;
import com.feihua.starter.service.modules.hdb.dto.HdbUserExtendDto;
import com.feihua.starter.service.modules.hdb.dto.SearchHdbActivitysConditionDto;
import com.feihua.utils.http.httpServletResponse.ResponseCode;
import feihua.jdbc.api.pojo.PageAndOrderbyParamDto;
import feihua.jdbc.api.pojo.PageResultDto;
import feihua.jdbc.api.utils.OrderbyUtils;
import feihua.jdbc.api.utils.PageUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 活动吧活动管理
 * Created by revolver
 */
@RestController
@RequestMapping("/hdb")
public class HdbActivityController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(HdbActivityController.class);

    @Autowired
    private ApiHdbActivityPoService apiHdbActivityPoService;
    @Autowired
    private ApiHdbImagePoService apiHdbImagePoService;

    @Autowired
    private ApiHdbUserExtendPoService apiHdbUserExtendPoService;

    @Autowired
    private ApiHdbScenicSpotPoService apiHdbScenicSpotPoService;

    /**
     * 单资源图片，删除
     *
     * @param id
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:image:delete")
    @RequestMapping(value = "/image/{id}", method = RequestMethod.DELETE)
    public ResponseEntity deleteImage(@PathVariable String id) throws Exception {
        logger.info("删除活动吧图片开始");
        logger.info("用户id:{}", getLoginUser().getId());
        logger.info("活动吧图片id:{}", id);
        ResponseJsonRender resultData = new ResponseJsonRender();

        int r = apiHdbImagePoService.deleteFlagByPrimaryKeyWithUpdateUser(id, getLoginUser().getId());
        if (r <= 0) {
            // 删除失败，可能没有找到资源
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("删除活动吧图片结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 删除成功
            logger.info("删除的活动吧图片id:{}", id);
            logger.info("删除活动吧图片结束，成功");
            return new ResponseEntity(resultData, HttpStatus.NO_CONTENT);
        }
    }

    /**
     * 单资源景点，删除
     *
     * @param id
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:scenicspot:delete")
    @RequestMapping(value = "/scenicspot/{id}", method = RequestMethod.DELETE)
    public ResponseEntity deleteScenicspot(@PathVariable String id) throws Exception {
        logger.info("删除活动吧景点开始");
        logger.info("用户id:{}", getLoginUser().getId());
        logger.info("活动吧景点id:{}", id);
        ResponseJsonRender resultData = new ResponseJsonRender();

        int r = apiHdbScenicSpotPoService.deleteFlagByPrimaryKeyWithUpdateUser(id, getLoginUser().getId());
        if (r <= 0) {
            // 删除失败，可能没有找到资源
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("删除活动吧景点结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 删除成功
            logger.info("删除的活动吧景点id:{}", id);
            logger.info("删除活动吧景点结束，成功");
            return new ResponseEntity(resultData, HttpStatus.NO_CONTENT);
        }
    }

    /**
     * 单资源，添加
     *
     * @param hdbActivityDto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:activity:add")
    @RequestMapping(value = "activity", method = RequestMethod.POST)
    public ResponseEntity add(@RequestBody HdbActivityDto hdbActivityDto) throws Exception{
        logger.info("添加活动吧活动开始");
        logger.info("当前登录用户id:{}", getLoginUser().getId());
        ResponseJsonRender resultData = new ResponseJsonRender();
        // 表单值设置
        //todo
        hdbActivityDto.setCreateBy(getLoginUserId());
        HdbActivityDto r = apiHdbActivityPoService.addOrUpdateHdbActivity(hdbActivityDto, false);
        if (r == null) {
            // 添加失败
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("添加活动吧活动结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 添加成功，返回添加的数据
            resultData.setData(r);
            logger.info("添加活动吧活动id:{}", r.getId());
            logger.info("添加活动吧活动结束，成功");
            return new ResponseEntity(resultData, HttpStatus.CREATED);
        }
    }

    /**
     * 单资源，删除
     *
     * @param id
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:activity:delete")
    @RequestMapping(value = "/activity/{id}", method = RequestMethod.DELETE)
    public ResponseEntity delete(@PathVariable String id) throws Exception {
        logger.info("删除活动吧活动开始");
        logger.info("活动id:{}", getLoginUser().getId());
        logger.info("活动吧活动id:{}", id);
        ResponseJsonRender resultData = new ResponseJsonRender();

        int r = apiHdbActivityPoService.deleteFlagByPrimaryKeyWithUpdateUser(id, getLoginUser().getId());
        if (r <= 0) {
            // 删除失败，可能没有找到资源
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("删除活动吧活动结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 删除成功
            logger.info("删除的活动吧活动id:{}", id);
            logger.info("删除活动吧活动结束，成功");
            return new ResponseEntity(resultData, HttpStatus.NO_CONTENT);
        }
    }

    /**
     * 单资源，更新
     *
     * @param id
     * @param hdbActivityDto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:activity:update")
    @RequestMapping(value = "/activity/{id}", method = RequestMethod.PUT)
    public ResponseEntity update(@PathVariable String id, @RequestBody HdbActivityDto hdbActivityDto) throws Exception {
        logger.info("更新活动吧活动开始");
        logger.info("当前登录用户id:{}", getLoginUser().getId());
        logger.info("活动吧活动id:{}", id);
        ResponseJsonRender resultData = new ResponseJsonRender();
        // 表单值设置
        hdbActivityDto.setUpdateBy(getLoginUserId());
        HdbActivityDto r = apiHdbActivityPoService.addOrUpdateHdbActivity(hdbActivityDto, true);

        // 用条件更新，乐观锁机制
        if (r == null) {
            // 更新失败，资源不存在
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("更新活动吧活动结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 更新成功，已被成功创建
            logger.info("更新的活动吧活动id:{}", id);
            logger.info("更新活动吧活动结束，成功");
            return new ResponseEntity(resultData, HttpStatus.CREATED);
        }
    }

    /**
     * 单资源，活动审核
     *
     * @param hdbReviewDto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:activity:review")
    @RequestMapping(value = "/activity/review", method = RequestMethod.PUT)
    public ResponseEntity activityReview(@RequestBody HdbReviewDto hdbReviewDto) throws Exception {
        logger.info("审核活动吧活动开始");
        logger.info("当前登录用户id:{}", getLoginUser().getId());
        logger.info("活动吧审核:{}", hdbReviewDto);
        ResponseJsonRender resultData = new ResponseJsonRender();
        // 表单值设置
        hdbReviewDto.setLoginUserId(getLoginUserId());
        final int i = apiHdbActivityPoService.activityReview(hdbReviewDto);

        //用条件更新，乐观锁机制
        if (i <= 0) {
            // 更新失败，资源不存在
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("审核活动吧活动结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 更新成功，已被成功创建
            logger.info("审核的活动吧活动id:{}", hdbReviewDto.getActivityId());
            logger.info("审核活动吧活动结束，成功");
            return new ResponseEntity(resultData, HttpStatus.CREATED);
        }
    }    /**
     * 单资源，活动审核查询
     *
     * @param dto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:activity:review:count")
    @RequestMapping(value = "/activity/review/count", method = RequestMethod.GET)
    public ResponseEntity activityReviewCount(SearchHdbActivitysConditionDto dto) throws Exception {
        HdbUserExtendDto baseDataScopeDto = apiHdbUserExtendPoService.selectByUserId(getLoginUserId());
        logger.info("活动吧审核查询开始");
        if(Constants.AuthUserType.MANAGER.getCode().equals(baseDataScopeDto.getType())){
            dto.setUserId(getLoginUserId());
        }
        ResponseJsonRender resultData = new ResponseJsonRender();
        PageAndOrderbyParamDto pageAndOrderbyParamDto = new PageAndOrderbyParamDto(PageUtils.getPageFromThreadLocal(), OrderbyUtils.getOrderbyFromThreadLocal());
        // 设置当前登录用户id
        PageResultDto<HdbActivityDto> list = apiHdbActivityPoService.searchByMultiTable(dto, pageAndOrderbyParamDto);

        logger.info("活动吧审核查询结束");
        if (CollectionUtils.isNotEmpty(list.getData())) {
            resultData.setData(list.getData().size());
            return new ResponseEntity(resultData, HttpStatus.OK);
        } else {
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 单资源，获取id活动吧活动
     *
     * @param id
     *
     * @return
     */
    @RequiresPermissions("hdb:activity:getById")
    @RequestMapping(value = "/activity/{id}", method = RequestMethod.GET)
    public ResponseEntity getById(@PathVariable String id) {

        ResponseJsonRender resultData = new ResponseJsonRender();
        HdbActivityDto baseDataScopeDto = apiHdbActivityPoService.selectById(id);
        if (baseDataScopeDto != null) {
            resultData.setData(baseDataScopeDto);
            return new ResponseEntity(resultData, HttpStatus.OK);
        } else {
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        }
    }


    /**
     * 复制活动，获取id活动吧活动
     *
     * @param id
     *
     * @return
     */
    @RequiresPermissions("hdb:activity:copyById")
    @RequestMapping(value = "/activity/copy/{id}", method = RequestMethod.PUT)
    public ResponseEntity copyActivity(@PathVariable String id) throws Exception {

        ResponseJsonRender resultData = new ResponseJsonRender();
        HdbActivityDto baseDataScopeDto = apiHdbActivityPoService.copyActivity(id, getLoginUserId());
        if (baseDataScopeDto != null) {
            resultData.setData(baseDataScopeDto);
            return new ResponseEntity(resultData, HttpStatus.OK);
        } else {
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 复数资源，搜索活动吧活动
     *
     * @param dto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:activity:search")
    @RequestMapping(value = "/activitys", method = RequestMethod.GET)
    public ResponseEntity search(SearchHdbActivitysConditionDto dto) {
        if(Constants.AuthUserType.MANAGER.getCode().equals(dto.getUserType())){
            dto.setUserId(getLoginUserId());
        }
        ResponseJsonRender resultData = new ResponseJsonRender();
        PageAndOrderbyParamDto pageAndOrderbyParamDto = new PageAndOrderbyParamDto(PageUtils.getPageFromThreadLocal(), OrderbyUtils.getOrderbyFromThreadLocal());
        // 设置当前登录用户id
        PageResultDto<HdbActivityDto> list = apiHdbActivityPoService.searchByMultiTable(dto, pageAndOrderbyParamDto);

        if (CollectionUtils.isNotEmpty(list.getData())) {
            resultData.setData(list.getData());
            resultData.setPage(list.getPage());
            return new ResponseEntity(resultData, HttpStatus.OK);
        } else {
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        }
    }
}
